package com.leyou.cart.controller;

import com.leyou.cart.pojo.Cart;
import com.leyou.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/8
 * Time: 11:34
 * *
 */
@Controller
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 添加到购物车（保存到redis）
     * @param cart
     * @return
     */
    @PostMapping("save")
    public ResponseEntity<Void> addCart(@RequestBody Cart cart) {
        this.cartService.addCart(cart);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<List<Cart>> queryCartList() {
        List<Cart> cartList = this.cartService.queryCartList();
        if (CollectionUtils.isEmpty(cartList)) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(cartList);
    }

    /**
     * 更新购物车（num）
     * @param cart
     * @return
     */
    @PostMapping("update")
    public ResponseEntity<Void> updateNum(@RequestBody Cart cart) {
        this.cartService.updateNum(cart);
        return ResponseEntity.noContent().build();
    }


    /**
     * 删除购物车
     * @param skuId
     * @return
     */
    @DeleteMapping("{skuId}")
    public ResponseEntity<Void> deleteCart(@PathVariable("skuId") Long skuId) {
        this.cartService.deleteCart(skuId);
        return ResponseEntity.noContent().build();
    }
}
